package com.example.refi.controller;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@EnableAutoConfiguration
public class FileCOntroller {
    @PostMapping("/uppic")
    public String getFile(@RequestParam("file") MultipartFile file) {
        System.out.println("收到请求");

        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = file.getOriginalFilename();
        String filePath = "C:\\Users\\96589\\Pictures\\";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            System.out.println("上传成功");
            return fileName;
        } catch (IOException e) {
            System.out.println("上传失败");
            System.out.println(e.getMessage());
        }
        return "上传失败！";
    }

    @GetMapping(value = "/pic", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getPicture(@RequestParam("name") String name) {
        System.out.println("请求图片");
        String filePath = "C:\\Users\\96589\\Pictures\\";
        File file = new File(filePath + name);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return null;

    }

}
